package com.banwoqiche.security;
import com.banwoqiche.mapper.SysUserMapper;
import com.banwoqiche.pojo.SysUser;
import com.banwoqiche.pojo.MySecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;

/**
 * @time: 2022-03-30 09:40
 */
@Component
public class MySecurityService implements UserDetailsService {
 private CUserMapper cUserMapper;

 @Autowired
 public void setcUserMapper(CUserMapper cUserMapper) {
  this.cUserMapper = cUserMapper;
 }
 /**
  * @param userAccount
  * @return
  * @throws UsernameNotFoundException
  */
 @Override
 public UserDetails loadUserByUsername(String userAccount) throws UsernameNotFoundException {

  Long sendId = null;
  //两种情况同时检查
  CUser userByaccount = cUserMapper.getUserByaccount(userAccount);
  CUser userBymobile = cUserMapper.getUserBymobile(userAccount);

  if (userByaccount == null && userBymobile == null) {
   throw new UsernameNotFoundException("用户不存在");
  }
  if (userByaccount.getcStatus() == 0 || userBymobile.getcStatus() == 0) {
   throw new UsernameNotFoundException("账户已停用");
  }
  //返回
  if (userByaccount.getcPwd() != null) {
   sendId = userByaccount.getcId();
   return new MySecurityUser(userAccount, userByaccount.getcPwd(), new ArrayList<>(), sendId);
  } else if (userBymobile.getcPwd() != null) {
   sendId = userBymobile.getcId();
   return new MySecurityUser(userAccount, userBymobile.getcPwd(), new ArrayList<>(), sendId);
  } else {
   throw new UsernameNotFoundException("用户登录错误，请检查登录验证方法！");
  }
 }
}

